package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"strings"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysCourse struct {
	api.Api
}

// GetPage
// @Summary 列表课程信息数据
// @Description 获取JSON
// @Tags 课程
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user [get]
// @Security Bearer
func (e SysCourse) GetPages(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysCourseList, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e SysCourse) GetPagesApp(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//上架状态
	req.Status = 1
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysCourseList, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 创建课程
// @Description 获取JSON
// @Tags 课程
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysCourseInsertReq true "课程数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-course [post]
// @Security Bearer
func (e SysCourse) Insert(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	lastID, insetErr := s.Insert(&req)
	if insetErr != nil {
		xlog.Error(insetErr)
		e.Error(500, insetErr, insetErr.Error())
		return
	}

	e.OK(lastID, "创建成功")
}

// Get
// @Summary 获取课程
// @Description 获取JSON
// @Tags 课程
// @Param userId path int true "课程编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user/{userId} [get]
// @Security Bearer
func (e SysCourse) Get(c *gin.Context) {
	s := service.SysCourse{}
	s1 := service.SysCourseGift{}
	req := dto.SysCourseById{}

	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		MakeService(&s1.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var data models.SysCourse
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &data)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}

	list, err := s1.Get(data.CourseId, "online")
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}
	//获取讲师信息
	ss := service.SysLecturer{}
	ss.Orm = e.Orm
	reql := dto.SysLecturerById{}
	reql.Id = data.LecturerId
	var object models.SysLecturer
	// 没有讲师就没有讲师嘛
	_ = ss.Get(&reql, p, &object)
	//if !strings.EqualFold(err.Error(), gorm.ErrRecordNotFound.Error()) {
	//	e.Error(http.StatusUnprocessableEntity, err, "查询失败")
	//	return
	//}

	result := models.SysCourseGetDetail{
		CourseId: data.CourseId,
		Step3:    object,
		Step1: models.Step1{
			SerialNum:          data.SerialNum,
			Subject:            data.Subject,
			Name:               data.Name,
			Cover:              data.Cover,
			Outline:            data.Outline,
			Price:              data.Price,
			Introduction:       data.Introduction,
			Announcement:       data.Announcement,
			AuditionLink:       data.AuditionLink,
			AuditionCourseName: data.AuditionCourseName,
			Status:             data.Status,
			PublicRange:        data.PublicRange,
			Province:           data.Province,
		},
		Step2: models.Step2{
			LecturerId:     data.LecturerId,
			OnlineClassId:  data.OnlineClassId,
			Contacts:       data.Contacts,
			TermOfValidity: data.TermOfValidity,
			IsBindOffline:  data.IsBindOffline,
			Telephone:      data.Telephone,
			CourseType:     data.CourseType,
			LiveUrl:        data.LiveUrl,
			StartTime:      data.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:        data.EndTime.Format("2006-01-02 15:04:05"),
			IsBoutique:     data.IsBoutique,
			CourseGift:     list,
			Qq:             data.Qq,
		},
		CourseWareJson: data.CourseWareJson,
		ControlBy:      data.ControlBy,
		ModelTime:      data.ModelTime,
	}

	e.OK(result, "查询成功")
}

func (e SysCourse) GetInternal(c *gin.Context, buyerId int) (models.SysCourseGetDetail, error) {
	result := models.SysCourseGetDetail{}
	s := service.SysCourse{}
	s1 := service.SysCourseGift{}
	req := dto.SysCourseById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		MakeService(&s1.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		return result, err
	}
	var data models.SysCourse
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &data)
	if err != nil {
		//e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return result, err
	}

	list, err := s1.Get(data.CourseId, "online")
	if err != nil {
		//e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return result, err
	}
	//获取讲师信息
	ss := service.SysLecturer{}
	ss.Orm = e.Orm
	reql := dto.SysLecturerById{}
	reql.Id = data.LecturerId
	var object models.SysLecturer
	err = ss.Get(&reql, p, &object)
	if err != nil {
		xlog.Error(err)
		//e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		//return result, err
	}
	//todo 判断是否有权限（是否购买）
	isBuy := 2
	if buyerId > 0 {
		id := 0
		err = e.Orm.Table("sys_learning_list").Select("id").Where("buyer_id=? and course_id=?", buyerId, data.CourseId).Scan(&id).Error
		if err != nil {
			xlog.Warnf("db error: %s", err)
		}
		if id != 0 {
			isBuy = 1
		}
	}
	result = models.SysCourseGetDetail{
		IsBuy:    isBuy,
		CourseId: data.CourseId,
		Step3:    object,
		Step1: models.Step1{
			SerialNum:          data.SerialNum,
			Subject:            data.Subject,
			Name:               data.Name,
			Cover:              data.Cover,
			Outline:            data.Outline,
			Price:              data.Price,
			Introduction:       data.Introduction,
			Announcement:       data.Announcement,
			AuditionLink:       data.AuditionLink,
			AuditionCourseName: data.AuditionCourseName,
			Status:             data.Status,
			PublicRange:        data.PublicRange,
			Province:           data.Province,
		},
		Step2: models.Step2{
			LecturerId:     data.LecturerId,
			OnlineClassId:  data.OnlineClassId,
			Contacts:       data.Contacts,
			TermOfValidity: data.TermOfValidity,
			IsBindOffline:  data.IsBindOffline,
			Telephone:      data.Telephone,
			CourseType:     data.CourseType,
			LiveUrl:        data.LiveUrl,
			StartTime:      data.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:        data.EndTime.Format("2006-01-02 15:04:05"),
			IsBoutique:     data.IsBoutique,
			CourseGift:     list,
		},
		CourseWareJson: data.CourseWareJson,
		ControlBy:      data.ControlBy,
		ModelTime:      data.ModelTime,
	}

	return result, nil
}

func (e SysCourse) ChangeStatus(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseUpdateStatusReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.UpdateStatus(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

func (e SysCourse) Update(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除班级数据
// @Description 删除数据
// @Tags 班级
// @Param userId path int true "classId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [delete]
// @Security Bearer
func (e SysCourse) Delete(c *gin.Context) {
	s := service.SysCourse{}
	req := dto.SysCourseById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 设置删除人
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

func (e SysCourse) GetBindingCourseList(c *gin.Context) {
	s := service.SysCourse{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	list := make([]models.CourseList, 0)
	err = s.GetBindingCourseList(&list)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(list, "Success")
	return
}
